<?php
require('cache.php');

/**
 * 获取连接
 * @return resource
 */
function getConnection(){
	$conn = mysql_connect ( '127.0.0.1', 'imedia', 'rm87!a^]1' );
	if (!$conn){
		die('Could not connect: ' . mysql_error());
	} 
	else{
		mysql_query("set names 'utf8'");
		return $conn;
	}
}

/**
 * 获取某表数据条数
 * @param $table
 * @return number
 */
function getCount($table){
	$conn = getConnection();
	mysql_select_db("imedia");
	$query = sprintf('select count(*) from %s ', $table);
	$result = mysql_query($query);
	$num = 0;
	while (@$row = mysql_fetch_array($result)) {
		$num = $row[0];
	}
	return $num;
}

/**
 * 加载所有数据到缓存
 * @param $limit
 */
function getDataFromDb($limit = 1000){
	$start_time = microtime(true);
	//需要加入缓存的表
	$need_mem_table = array(
		'ad_media','ad_ment','ad_order','chain_activity',
		'chain_comment','chain_part','chain_product',
		'customer','edu_config','edu_msg','edu_school',
		'edu_student','edu_study','edu_subject',
		'edu_subject_s','im_city','order',
		'order_product','p_area','p_class',
		'p_comment','p_standard','product',
		'region','region_school','shop_config',
		'vancl','wap_use'
	);
	$log_dir = 'message.'. php_uname('n') . '.' . date('Ymd') . '.log';
	$conn = getConnection();
	$dbname = 'imedia';
	$result = mysql_list_tables($dbname);
    if (!$result) die('DB Error, could not list tables:' . mysql_error());
    $cache = new Cache();
    $cache->flush();
    $count_all = 0;
    while ($row = mysql_fetch_row($result)) {
        $table = $row[0];
	    $count = getCount($table);
	    if (in_array($table, $need_mem_table) && $count != 0) {
		    $count_all += $count;
		    //模拟人工分页查找算法
		    for ($i = 0; $i < $count; $i += $limit) {
			    $query = sprintf(" select * from %s limit %s, %s ", $table, $i, $limit);
			    print $query;
			    $results = mysql_query($query);
			    while ($row = mysql_fetch_array($results)) {
			    	$id = $row[0];
			    	$cache->set($table . '_' . $id, $row);
			    }
			    mysql_free_result($results);
		    }
	    }
    }
    mysql_free_result($result);
    
    //关闭连接
    mysql_close($conn);
    $cache->close();
    
    //做记录
    $time = microtime(true) - $start_time;
    $now = date('Y-m-d H:i:s');
$info = <<<EOF
$now 耗时: $time 秒, 加载 $count_all 条数据 ;
EOF;
	trace($info, $log_dir);
}





// 记录运行操作日志
function trace($message, $logfile) {
	create_directory ( $logfile );
	$log = fopen ( $logfile, 'ab' );
	flock ( $log, LOCK_EX );
	fwrite ( $log, date ( 'Y-m-d H:i:s' ) . '`' . $message . "\n" );
	flock ( $log, LOCK_UN );
	fclose ( $log );
}

function create_directory($file) {
	if (! file_exists ( $file )) {
		$file_path = dirname ( $file );
		if (! is_dir ( $file_path )) {
			return mkdir ( $file_path, 0700, true );
		}
	}
	return true;
}


//测试 每次加载1000条
getDataFromDb();